package com.cloudm.technician.ui.base

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.support.v4.content.FileProvider
import com.blankj.utilcode.util.FileUtils
import com.cloudm.technician.R
import com.cloudm.technician.extensions.*
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File


/**
 * 作者: wesley
 * 时间: 2017/12/22
 * 描述: 上传照片相关的ui
 */
abstract class BaseFileFragment<T : BasePresenter> : BaseFragment<T>() {

    protected var file: File? = null

    private val dirPath by lazy {
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).absolutePath
    }

    companion object {
        const val REQUEST_CODE_CAMERA = 1024
        const val REQUEST_CODE_IMAGE_FROM_ALBUM = 1025
    }

    private fun checkFileIsCreateSuccess(): Boolean {
        file = createNewFile()
        return file != null
    }

    private fun createNewFile(): File? {
        if (!isSDCardEnable()) {
            mContext.toast(mContext.resources.getString(R.string.sdcoad_is_not_enabled))
            return null
        }
        val dir = getSDCardPath() + mContext.packageName + "/camera/"
        if (!FileUtils.createOrExistsDir(dir)) {
            mContext.toast(mContext.resources.getString(R.string.dir_create_failure))
            return null
        }
        val imagePath = dir + System.currentTimeMillis() + ".png"
        val file = File(imagePath)
        if (!FileUtils.createFileByDeleteOldFile(file)) {
            mContext.toast(mContext.resources.getString(R.string.dir_create_failure))
            return null
        }
        return file
    }


    fun takePictureFromCamera() {
        if (!checkFileIsCreateSuccess()) {
            mContext.logger_e("BaseFileFragment", "takePicture file create failure ")
            return
        }
        val intentCamera = Intent()
        intentCamera.action = MediaStore.ACTION_IMAGE_CAPTURE
        var uri: Uri? = null
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            file?.let {
                uri = FileProvider.getUriForFile(mContext, mContext.packageName + ".fileProvider",
                        it)
                val resInfoList = mContext.packageManager?.queryIntentActivities(intentCamera,
                        PackageManager.MATCH_DEFAULT_ONLY)
                resInfoList?.map { it.activityInfo.packageName }?.forEach {
                    mContext.grantUriPermission(it, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                }
            }

        } else {
            uri = Uri.fromFile(file)
        }
        intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, uri)
        if (intentCamera.resolveActivity(mContext.packageManager) == null) {
            mContext.toast(mContext.resources.getString(R.string.camera_not_found))
            return
        }
        startActivityForResult(intentCamera, REQUEST_CODE_CAMERA)
    }

    fun takePicFromGalley() {
        val intent = Intent(Intent.ACTION_PICK).apply {
            setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
        }
        if (intent.resolveActivity(mContext.packageManager) == null) {
            mContext.toast(mContext.resources.getString(R.string.galley_not_found))
            return
        }
        startActivityForResult(intent, REQUEST_CODE_IMAGE_FROM_ALBUM)
    }

    fun compressImageByLuban(filePath: String, onSuccess: (File) -> Unit,
                             onFailure: (String?) -> Unit) {
        Luban.with(mContext).load(filePath).setCompressListener(object : OnCompressListener {
            override fun onStart() {

            }

            override fun onSuccess(file: File) {
                onSuccess(file)
            }

            override fun onError(e: Throwable) {
                onFailure(e.message)
            }
        }).launch()
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) {
            return
        }
        when (requestCode) {
            REQUEST_CODE_CAMERA -> {
                when (file) {
                    null -> mContext.toast(
                            mContext.resources.getString(R.string.pic_upload_failure))
                    else -> {
                        val path = file?.absolutePath ?: ""
                        takePictureSuccess(path)
                    }
                }
            }

            REQUEST_CODE_IMAGE_FROM_ALBUM -> {
                val path = data?.data?.parseUriToPath(mContext) ?: ""
                takeFromGalleySuccess(path)
            }
        }
    }


    /**
     * 拍照成功---图片路径
     */
    open fun takePictureSuccess(path: String) {

    }


    /**
     * 从相册中选取成功
     */
    open fun takeFromGalleySuccess(path: String) {

    }
}